/* User preferences to externalise */

var start = 0;
var pageSize = 50;
var showImages = "Yes";

function userDisplay(data) {

	if ($(data).find("Responses > UserInfo > Error").length == 0) {
		displayUserInfo(data);
		$("#loggedInSection").show();
	} else {
		$("#loginSection").show();
	}

}

function siteInfoDisplay(data) {

	var userCount = $(data).find("Responses > SiteInfo > UserCount").text();
	var threadCount = $(data).find("Responses > SiteInfo > ThreadCount").text();
	var messageCount = $(data).find("Responses > SiteInfo > MessageCount").text();
	var activeUsers = $(data).find("Responses > SiteInfo > ActiveUsers").text();

	userCount = Globalize.format(parseInt(userCount), "n0");
	threadCount = Globalize.format(parseInt(threadCount), "n0");
	messageCount = Globalize.format(parseInt(messageCount), "n0");
	activeUsers = Globalize.format(parseInt(activeUsers), "n0");

	$("#userCountTextField").html(userCount);
	$("#threadCountTextField").html(threadCount);
	$("#messageCountTextField").html(messageCount);
	$("#activeUsersTextField").html(activeUsers);
}

function boardDisplay(data) {

	$("#boardLink").hide();

	var html = "<table id='boardsTable' class='table'>";

	html += "<thead class='tablehead'><th class='tableheadcell'>Board Name</th><th class='tableheadcell'>Board Description</th></thead>";

	$(data).find("Responses > Boards > Board").each(function() {

		var name = $(this).find("Name").text();
		var boardId = $(this).find("BoardId").text();
		var description = $(this).find("Description").text();
		var privateBoard = $(this).find("Private").text();
		var popularBoard = $(this).find("Popular").text();

		html += "<tr class='row'>";
		html += "<td class='cell'>";

		if (popularBoard == "Yes") {
			html += "<span class='popularBoard'>";
		}

		html += "<a class='threadLink' href='#" + boardId + "'>" + name + "</a>";

		if (popularBoard == "Yes") {
			html += "</span>";
		}

		if (privateBoard == "Yes") {
			html += "<span class='privateBoard'> [Private]</span>";
		}

		html += "<td class='cell'>" + description + "</td>";
		html += "</tr>";

	});

	html += "</table>";

	$("body").scrollTop(0);
	$("#mainPanel").html(html);
	$("#xml").text(serialiseXml(data));

}

function newAnswersDisplay(data) {

	var boardName = $(data).find("Responses > RecentlyUpdatedThreads > BoardName").text();

	/* Add on the board link after the home page link */
	$("#boardLink").html(" <span class='boardLink'>&gt; " + boardName + "</span>").show();

	var html = "<h2 id='newAnswersBoardName'>" + boardName + "</h2><ul>";

	$(data).find("Responses > RecentlyUpdatedThreads > Thread").each(function() {
		var title = $(this).find("Title").text();
		var boardId = $(this).find("BoardId").text();
		var threadId = $(this).find("ThreadId").text();
		var poll = $(this).find("Poll").text();
		html += "<li><a onclick='threadClicked(event)' href='#" + boardId + "-" + threadId + "'>";

		if (poll == "Yes") {
			html += "<span class='pollThreadIdentifier'>[Poll] </span>";
		}

		html += title + "</a></li>";
	});

	html += "</ul>";

	$("#mainPanel").html(html);
	$("#xml").text(serialiseXml(data));

	/* Scroll to the top, as the page will stay in the same position */
	$("body").scrollTop(0);

}

function newAnswersCallback(data, status, request) {
	newAnswersDisplay(data);
}

function newAnswersSelected(boardId) {

	/* Request the new answers for the given board */

	var xml = "<Requests>" + newAnswersMessage(boardId) + "</Requests>";

	sendMessage(xml, newAnswersCallback);
}

/* When you select a board from the boards list */

function newAnswersClicked(event) {

	/* Get the board ID from the URL */

	var url = event.currentTarget.href;
	var boardIdExpression = new RegExp(".*#(.*)");
	var boardId = boardIdExpression.exec(url)[1];

	newAnswersSelected(boardId);
}

// TODO Probably shouldn't show the voting buttons if you're not logged in

function getPollHtml(boardId, threadId, data) {

	var pollHtml = "";

	var pollClosingDate = $(data).find("Responses > Thread > PollClosingDate").text();
	var pollResults = $(data).find("Responses > Thread > PollResults");

	if (pollResults.length != 0) {

		pollHtml += "<p class='pollClosingDate'>Poll closed on " + pollClosingDate + "</p>";
		pollHtml += "<table id='pollTable' class='table'>";
		pollHtml += "<thead class='tablehead'><th class='tableheadcell'>Option</th><th class='tableheadcell'># Votes</th></thead>";

		$(data).find("Responses > Thread > PollResults > Result").each(function() {

			var option = $(this).find("Option").text();
			var voteCount = $(this).find("VoteCount").text();

			pollHtml += "<tr class='row'>";
			pollHtml += "<td class='cell'>" + option + "</td>";
			pollHtml += "<td class='cell'>" + voteCount + "</td>";
			pollHtml += "</tr>";
		});

		pollHtml += "</table>";

	} else {

		pollHtml += "<p class='pollClosingDate'>Poll closed on " + pollClosingDate + "</p>";
		pollHtml += "<table id='pollTable' class='table'>";
		pollHtml += "<thead class='tablehead'><th class='tableheadcell'>Option</th><th class='tableheadcell'>Vote</th></thead>";

		var voted = $(data).find("Responses > Thread > Voted").text();
		var votedFor = $(data).find("Responses > Thread > VotedFor").text();

		$(data).find("Responses > Thread > PollOptions > Option").each(function() {

			var id = $(this).find("Id").text();
			var text = $(this).find("Text").text();

			pollHtml += "<tr class='row'>";
			pollHtml += "<td class='cell'>" + text + "</td>";

			if (voted == "No") {
				pollHtml += "<td class='cell'><input onclick='voteFor(event, " + boardId + ", " + threadId + ", " + id + ")' type='button' class='voteButton' value='Vote'></input></td>";
				pollHtml += "</tr>";
			} else {
				if (id == votedFor) {
					pollHtml += "<td class='cell'>You voted for this option</td>";
					pollHtml += "</tr>";
				} else {
					pollHtml += "<td class='cell'></td>";
					pollHtml += "</tr>";
				}
			}
		});

		pollHtml += "</table>";
	}
	return pollHtml;
}

function threadDisplay(data) {

	var html = "";

	var boardName = $(data).find("Responses > Thread > BoardName").text();
	$("#boardLink").html(" <span class='boardLink'>&gt; " + boardName + "</span>").show();

	/* First the thread title */

	var title = $(data).find("Responses > Thread > Title").text();
	var boardId = $(data).find("Responses > Thread > BoardId").text();
	var threadId = $(data).find("Responses > Thread > ThreadId").text();
	var messageCount = $(data).find("Responses > Thread > MessageCount").text();
	var creatorId = $(data).find("Responses > Thread > CreatorId").text();
	var creationDate = $(data).find("Responses > Thread > CreatedOn").text();
	
	var date = new Date();
	date.setISO(creationDate);
	creationDate = Globalize.format(date, "MMMM yyyy");
	
	html += "<h2>" + title + "</h2>";
	html += "<p><span id='threadNumberOfPosts'>" + messageCount + "</span> posts, started by <span id='threadCreatorId'>" + creatorId + "</span> in <span id='threadCreationDate'>" + creationDate + "</span></p>";
	html += "<hr class='rule'></hr>";
	
	
	var poll = $(data).find("Responses > Thread > Poll").text();

	if (poll == "Yes") {
		html += "<section class='pollSection' id='pollSection'>";
		html += getPollHtml(boardId, threadId, data);
		html += "</section>";
	}

	$(data).find("Responses > Thread > Messages > Message").each(function() {

		var body = $(this).find("Body").text();
		var displayName = $(this).find("DisplayName").text();
		var timestamp = $(this).find("Timestamp").text();
		var messageId = $(this).find("MessageId").text();

		var date = new Date();
		date.setISO(timestamp);
		timestamp = Globalize.format(date, "D");

		html += "<div class='post' id='" + messageId + "'><p>" + body + "</p></div>";
		html += "<div class='postDetails'>";
		html += "<span class='displayName'>" + displayName + "</span>, ";
		html += "<span class='timestamp'>" + timestamp + "</span>";
		/* html += "<strong><span> Message ID: " + messageId + "</span></strong>"; */
		html += "</div>";
		html += "<hr class='rule'></hr>";
	});

	$("#mainPanel").html(html);
	$("#xml").text(serialiseXml(data));

	/* Scroll to the top, as the page will stay in the same position */
	$("body").scrollTop(0);

}

function threadSelectedCallback(data, status, request) {
	threadDisplay(data);
}

function threadSelected(boardId, threadId) {

	var xml = "<Requests>";
	xml += threadMessage(boardId, threadId, showImages, start, pageSize);
	xml += "</Requests>";

	sendMessage(xml, threadSelectedCallback);
}

/* When you select a thread from the new answers page */

function threadClicked(event) {

	var url = event.currentTarget.href;
	var idExpression = new RegExp(".*#(.*)-(.*)");
	var boardId = idExpression.exec(url)[1];
	var threadId = idExpression.exec(url)[2];

	threadSelected(boardId, threadId);
}